package org.projects.graduates.app.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.projects.graduates.app.GradApplication;
import org.projects.graduates.domain.ContentStatus;
import org.projects.graduates.domain.Course;
import org.projects.graduates.domain.HomeworkAssignments;
import org.projects.graduates.domain.HomeworkComment;
import org.projects.graduates.domain.HomeworkHandin;
import org.projects.graduates.domain.Person;
import org.projects.graduates.domain.Studying;
import org.projects.graduates.domain.Teaching;
import org.projects.graduates.page.Pager;

import com.dayatang.domain.AbstractEntity;
import com.dayatang.domain.EntityRepository;
import com.dayatang.domain.QuerySettings;

public class GradApplicationImpl implements GradApplication {

	public void save(AbstractEntity entity) {
		entity.save();
	}

	public void remove(AbstractEntity entity) {
		entity.remove();
	}

	public void setUp(Person teacher, Course course) {
		course.setEnable(true);
		course.save();
		Teaching teach = new Teaching();
		teach.setUp(teacher, course);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List page(Pager pager, QuerySettings settings, EntityRepository repository) {
		settings.setFirstResult(Integer.parseInt("" + pager.startLine()));
		settings.setMaxResults(Integer.parseInt("" + pager.getPageSize()));
		return repository.find(settings);
	}

	@SuppressWarnings("unchecked")
	public List<HomeworkHandin> handinsOfHomework(Pager pager, HomeworkAssignments ha, ContentStatus status,
			EntityRepository repository) {
		List<HomeworkHandin> results = new ArrayList<HomeworkHandin>();
		results.addAll(page(pager, QuerySettings.create(HomeworkHandin.class).eq("homework", ha).eq("status", status),
				repository));
		return results;
	}

	@SuppressWarnings("unchecked")
	public List<HomeworkComment> commentsOfHomeworkhandins(Pager pager, HomeworkHandin handin, EntityRepository repository) {
		List<HomeworkComment> results = new ArrayList<HomeworkComment>();
		results.addAll(page(pager, QuerySettings.create(HomeworkComment.class).eq("handin.id", handin.getId()), repository));
		return results;
	}

	public void scoreHomeworkHandin(HomeworkHandin handin, int score, Person who) {
		handin.setScore(score);
		handin.setTime(new Date());
		handin.setWhoScore(who);
		this.save(handin);
	}
	
	public boolean existShowname(String showName){
		return Person.findBy(showName) == null ? false : true;
	}

	public void selecCourse(Person person, Course course) {
		Studying stu = new Studying(person, course);
		this.save(stu);
	}

	
}
